//
//  WPCNetWorkingManager.m
//  Wallpaper.co
//
//  Created by zhou_yuepeng on 2017/9/4.
//  Copyright © 2017年 www.dahuatech.com. All rights reserved.
//

#import "WPCNetWorkingManager.h"
#import "WPCURLFactory.h"
#import "WPCThemesInfo.h"
#import "WPCDBManager.h"

#import "AFNetWorking.h"

@implementation WPCNetWorkingManager
+ (instancetype)shareInstance
{
    static WPCNetWorkingManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[WPCNetWorkingManager alloc] init];
    });
    
    return instance;
}

- (void)queryThemesInfoWithTag:(NSString*)tag page:(NSInteger)page success:(requestSuccess)success failure:(requestFailure)failure
{
    if (nil == success || nil == failure) {
        return;
    }
    
    if ([tag isEqualToString:@"favorites"]) {
        id object = [self loadFavoriteThemesFromDeskWithPage:page];
        success(object);
        return;
    }
    
    NSString *url = [WPCURLFactory getThemesUrlWithTag:tag page:page];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *error = nil;
        NSMutableArray *items = [WPCThemesItem arrayOfModelsFromDictionaries:responseObject error:&error];
        if (nil == items) {
            failure(error);
            return;
        }

        success(items);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

- (void)queryGeneralInfoWithSource:(NSString*)source model:(Class)modelCls success:(requestSuccess)success failure:(requestFailure)failure
{
    if (nil == success || nil == failure) {        
        return;
    }
    
    NSString *url = [WPCURLFactory getGeneralURLWithSource:source];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *error = nil;
        id model = [[modelCls alloc] initWithDictionary:responseObject error:&error];
        if (nil == model) {
            failure(error);
            return;
        }
        
        success(model);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

- (id)loadFavoriteThemesFromDeskWithPage:(NSInteger)page
{
    NSRange range = NSMakeRange((page-1)*12, 12);
    return [WPCDBManager queryFavoriteItemWithRange:range];
}

@end
